package com.obj.commpont.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Util {

    private static  final String MD5 = "MD5";

    /**
     * 字符编码
     */
    private static final String UTF_8 = "UTF-8";

    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * MD5加密加盐值
     *
     * @param origin
     * @return
     */
    public static String md5Encode(String origin,String salt) {
        String resultHex = origin + salt;
        return md5Encode(resultHex);
    }

    /**
     * MD5加密
     *
     * @param origin
     * @return
     */
    public static String md5Encode(String origin) {
        String resultHex = null;
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            byte[] digest = md.digest(origin.getBytes(UTF_8));
            resultHex = byteToString(digest);
        } catch (NoSuchAlgorithmException e) {

        } catch (UnsupportedEncodingException e) {

        }
        return resultHex;
    }

    /**
     * byte数组转16进制字符串
     *
     * @param data byte数组
     * @return 字符串
     */
    private static String byteToString(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = hexDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = hexDigits[0x0F & data[i]];
        }
        return new String(out);
    }

    public static void main(String[] args) {
        System.out.println(md5Encode("123456"));
    }

}
